import { Api } from '@/api'
import { storageLocal } from '@wxcn/utils'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { TOKEN } from './const'

export const useUserStore = defineStore('user', () => {
  /** token */
  const tokenDef = storageLocal.getItem(TOKEN)
  const token = ref(tokenDef ?? null)

  const isLogin = computed(() => token.value !== null)
  const setToken = (value: any) => {
    token.value = value
    storageLocal.setItem(TOKEN, { ...value, times: Date.now() })
  }

  /** user info */
  const userInfo = ref<Eps.AccountService.GetUserInfo>(null!)
  const setUserInfo = () => {
    Api.AccountService.GetUserInfo().then((res) => {
      userInfo.value = res
    })
  }

  const clearUserInfo = () => {
    token.value = null
    storageLocal.removeItem(TOKEN)
    userInfo.value = null!
  }
  return {
    isLogin,
    token,
    setToken,
    userInfo,
    setUserInfo,
    clearUserInfo,
  }
})
